const moment = require("moment");

module.exports = function(sequelize, DataTypes){
    var Menu = sequelize.define('AdminMenu', {
        menu_id: {
            type: DataTypes.BIGINT(20),
            allowNull: false,
            autoIncrement: true,
            primaryKey: true
        },
        parent_id: {
            type: DataTypes.BIGINT(20),
            allowNull: false
        },
        menu_name: {
            type: DataTypes.STRING(10)
        },
        menu_url: {
            type: DataTypes.STRING(50)
        },
        menu_icon: {
            type: DataTypes.STRING(50)
        },
        creator_id: {
            type: DataTypes.BIGINT(20),
            defaultValue: 0,
            allowNull: false
        },
        created_at: {
            type: DataTypes.DATE,
            defaultValue: new Date(),
            allowNull: false,
            get() {
                return moment(this.getDataValue('created_at')).format('YYYY-MM-DD HH:mm:ss');
            }
        },
        modified_id: {
            type: DataTypes.BIGINT(20),
            defaultValue: 0,
            allowNull: false
        },
        modified_at: {
            type: DataTypes.DATE,
            defaultValue: new Date(),
            allowNull: false,
            get() {
                return moment(this.getDataValue('modified_at')).format('YYYY-MM-DD HH:mm:ss');
            }
        },
        is_del: {
            type: DataTypes.TINYINT(1),
            defaultValue: 0
        }
    }, {
        timestamps: false,
        freezeTableName: true,
        tableName: 'system_menu',
    });

    Menu.schema("public");

    Menu.associate = function (model) {
        addMenuRoles(Menu, model.AdminRole);
    };

    Menu.destroyMenus = async function(menu_ids) {
        return sequelize.transaction().then(function (t) {
            this.t = t;
            return Menu.update({
                is_del: 1
            },{
                transaction: t,
                where: {
                    menu_id: menu_ids
                }
            });
        }).then(function() {
            return sequelize.query("DELETE FROM system_menu_role WHERE menu_id in ("+menu_ids.join(',')+");", {
                type: sequelize.QueryTypes.DELETE,
                transaction: this.t
            });
        }).then(function() {
            return this.t.commit();
        }).catch(function (err) {
            return this.t.rollback();
        });
    };

    // 同步模型到数据库
    Menu.sync({force: false}).then(function () {

    });

    return Menu;
};

function addMenuRoles(menu, role) {
    menu.belongsToMany(role, {
        as: 'MenuRoles',
        through: 'system_menu_role',
        timestamps: false,
        foreignKey: {
            name: 'menu_id',
            allowNull: false
        },
        otherKey: {
            name: 'role_id',
            allowNull: false
        }
    });
}
